<template>
    <div class="table-container" ref="table-container"
        :style="{ height: hasPagination ? 'calc(100% - 40px)' : '100%' }">
        <el-table :id="`elTable_${tableId}`" stripe v-tableMove :data="tableDataList" v-if="showTable"
            v-loading="loading" border fit highlight-current-row style="width: 100%;"
            @selection-change="handleSelectionChange" height="100%" @sort-change="handleSortChange"
            @row-click="handleRowClick"
            :header-cell-style="{ background: '#d6d6d6 !important', color: '#666  !important' }">
            <!-- 是否有多选 -->
            <el-table-column type="selection" width="55" v-if="table_config.isCheckBox || isSelect"
                :selectable="selectable"></el-table-column>
            <!-- 是否需要序号 -->
            <!-- <el-table-column type="index" label="序号" width="55" align="center" /> -->
            <el-table-column label="序号" width="55" align="center">
                <template slot-scope="scope">{{ scope.row.$index >= 0 ? scope.row.$index + 1 : '' }}</template>
            </el-table-column>
            <template v-for="item, index in itemList">
                <el-table-column v-if="item" :key="item.prop + '_' + index" :prop="item.prop" :label="item.label"
                    :min-width="item.minWidth" :sortable="item.sortable ? true : false" align="center">
                    <template slot-scope="scope">
                        <div v-if="scope.row.$index >= 0">
                            <!-- 自定义slot 插槽 -->
                            <div v-if="item.slotName">
                                <slot :name=item.slotName :row="scope.row"></slot>
                            </div>
                            <!-- 有状态过滤 -->
                            <span v-else-if="item.filter" :class="item.specialClass && item.specialClass(scope.row)">
                                {{ item.callback && item.callback(scope.row) }}
                            </span>
                            <!-- 图片展示 -->
                            <img v-else-if="item.image" :src="scope.row[item.prop]" style="width:40px; height: 40px">
                            <!-- switch开关 -->
                            <el-switch v-else-if="item.switch" v-model="scope.row[item.prop]" active-text="启用"
                                active-value=1 inactive-value=0 inactive-text="停用"
                                @change="item.callback && item.callback(scope.row)">
                            </el-switch>
                            <!-- 有跳转 -->
                            <router-link v-else-if="item.router"
                                :to="{ path: item.routerPath, query: { name: scope.row[item.prop] } }">
                                {{ scope.row[item.prop] }}
                            </router-link>
                            <!-- 默认展示 -->
                            <span v-else>{{ scope.row[item.prop] }}</span>
                        </div>
                    </template>
                </el-table-column>
            </template>

            <!-- 操作列 -->
            <el-table-column v-if="table_config.isOperation" :label="table_config.operation.label"
                :fixed="configFixed.flag" :width="table_config.operation.width" align="center">
                <template slot-scope="scope">
                    <div v-if="scope.row.$index >= 0">
                        <template v-if="table_config.operation.cols">
                            <div class="btn" v-for="item in table_config.operation.cols.slice(0, 5)" :key="item.label">
                                <!-- v-show="pageRoles.includes(item.flag)"这里控制权限 -->
                                <el-button v-show="pageRoles.includes(item.flag) || adminRole"
                                    @click="item.handleRow(scope.row, item)" plain :type="item.type" size="mini">
                                    {{ item.label }}
                                </el-button>
                            </div>
                        </template>
                        <!-- 操作列超过3个，用更多下拉显示 -->
                        <el-dropdown v-if="isShowOperationCols">
                            <span class="el-dropdown-link">
                                更多<i class="el-icon-arrow-down el-icon--right"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <!-- v-show="pageRoles.includes(item.flag)"这里控制权限 -->
                                <el-dropdown-item v-for="item in table_config.operation.cols.slice(2)" :key="item.label"
                                    v-show="pageRoles.includes(item.flag) || adminRole"
                                    @click.native="item.handleRow(scope.row, item.label)">
                                    {{ item.label }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination" v-if="hasPagination">
            <Pagination :page="page" :size="size" :total="total" :pageSizes="pageSizes" :layout="layout"
                @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></Pagination>
        </div>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Pagination from '../Pagination'
import elementResize from 'element-resize-detector'
export default {
    components: { Pagination },
    props: {
        hasPagination: {
            type: Boolean,
            default: true
        },
        layout: {
            type: String,
            default: () => {
                return "total, sizes, prev, pager, next, jumper"
            }
        },
        page: {
            type: Number,
            default: () => {
                return 1
            }
        },
        total: {
            type: Number,
            default: () => {
                return 100
            }
        },
        size: {
            type: Number,
            default: () => {
                return 10
            }
        },
        pageSizes: {
            type: Array,
            default: () => {
                return [4, 5, 10, 20, 30, 40, 50, 100, 200, 500, 1000]
            }
        },
        //打开设置栏
        openColumn: {
            type: Boolean,
            default: true
        },
        isSelect: {
            type: Boolean,
            default: false
        },
        configFixed: {
            type: Object,
            default: () => {
                return { flag: false }
            }
        },
        config: {
            type: Object,
            default: () => { }
        },
        dataList: {
            type: Array,
            default: () => {
                return []
            }
        },
        loading: {
            type: Boolean,
            default: false
        },
        tableThead: {
            type: Array,
            default: () => {
                return []
            }
        },
        tableId: {
            type: String,
            default: ''
        },
        tableItemNum: {
            type: Number,
            default: 10
        }
    },
    data() {
        return {
            adminRole: false,  //放开按钮权限
            showTable: true,
            table_config: {
                isCheckBox: false,    // 是否多选
                isOperation: false,   // 是否有操作列表
                operation: {        // 操作
                    cols: []
                },
            },
            tableDataList: [],
            dialogVisible: false,
            list: JSON.parse(JSON.stringify(this.tableThead)),
            itemList: this.tableThead,
            routerName: `${this.$route.name}_table`,
            erd: null
        }
    },
    computed: {
        ...mapGetters([
            'pageRoles'
        ]),
        rolesBtnList() {
            return this.btnList.filter(flag => this.pageRoles.includes(flag))
        },
        isShowOperationCols() {
            let list = this.table_config.operation.cols
            return list.length && list.length > 5
        }
    },
    watch: {
        total: {
            handler(v) {
                let npage = Math.ceil(v / this.size) || 1
                if (npage < this.page) {
                    this.handleCurrentChange(npage);
                }
            }
        },
        // 监听传过来的config，进行初始化
        config: {
            handler(newVal) {
                if (newVal) {
                    this.initConfig()
                }
            },
            immediate: true
        },
        dataList: {
            handler(newVal) {
                this.tableDataList = newVal;
                this.setTableHeight(this.dataList);
                setTimeout(() => {
                    this.listenToTable();
                }, 100)
            },
            deep: true
        },
        tableThead: {
            handler(v) {
                this.list = v;
                this.itemList = v;
            },
            deep: true
        }
    },
    mounted() {
        this.erd = elementResize();
        this.listenToTable();
    },
    methods: {
        selectable(row) {
            return row.$index >= 0
        },
        //监听table 高度
        listenToTable() {
            this.erd.listenTo(this.$refs['table-container'], element => {
                this.$nextTick(() => {
                    this.setTableHeight(this.dataList);
                })
            });
        },
        setTableHeight(dataList) {
            let table = document.getElementById(`elTable_${this.tableId}`);
            let tableBody = table.querySelectorAll('.el-table__body-wrapper')[0];
            let tableHeight = tableBody.clientHeight;
            // console.log('表格高度：', table, tableBody, tableHeight)
            // console.log(tableHeight, this.tableItemNum)
            let tableRowHeight = tableHeight / this.tableItemNum
            this.$nextTick(() => {
                let tableRow = document.querySelectorAll('.el-table__row');
                Array.from(tableRow).forEach(element => {
                    element.style.height = `${tableRowHeight <= 40 ? 40 : tableRowHeight}px`
                });
                // console.log(tableRowHeight)
                this.tableDataList = this.padArray(dataList, this.tableItemNum).map((e, i) => {
                    let objLength = Object.keys(e).length;
                    return { ...e, $index: objLength ? i : -1 }
                })
            })
        },
        padArray(arr, length = 10, padValue = {}) {
            while (arr.length < length) {
                arr.push(padValue);
            }
            return arr;
        },
        closeDialog() {
            this.dialogVisible = false
        },
        //刷新表单；
        refreshTable() {
            this.showTable = false;
            this.$nextTick(() => {
                this.showTable = true;
            })
        },
        // 初始化配置
        initConfig() {
            for (let key in this.config) {
                if (Object.keys(this.table_config).includes(key)) {
                    this.table_config[key] = this.config[key]
                }
            };
        },
        // 多选事件
        handleSelectionChange(val) {
            this.$emit('selection-change', val)
        },
        // 排序事件
        handleSortChange(val) {
            this.$emit('sort-change', val)
        },
        //点击事件
        handleRowClick(val) {
            this.$emit('row-click', val)
        },

        handleSizeChange(val) {
            this.$emit('handleSizeChange', val);
        },
        handleCurrentChange(val) {
            this.$emit('handleCurrentChange', val);
        }
    }
}
</script>

<style scoped>
.btn {
    display: flex;
    justify-content: center;
    display: inline-block;
    margin: 5px 0 0 10px;
}

.btn:first-child {
    margin-left: 0;
}

.color1 {
    color: red;
}

.color2 {
    color: green;
}

.color3 {
    color: blue;
}

.el-dropdown {
    margin-left: 10px;
    cursor: pointer;
}

.header-icon {
    cursor: pointer;
}

::v-deep .table {

    .el-table__fixed,
    .el-table__fixed-left,
    .el-table__fixed-right {
        height: calc(100% - 18px) !important;

        td {
            pointer-events: auto;
        }
    }

    tbody .el-table__cell {
        padding: 0;
    }

    .el-table {
        &:td {
            padding: 0 !important;
        }

        .cell {
            line-height: normal;
        }
    }


}

::v-deep .el-table .table-container {
    height: 100%;
}

.pagination {
    width: 100%;
    height: 40px;
    display: flex;
    justify-content: flex-end;
    align-items: flex-end;
}
</style>